package cs5226.tags;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class DbResultSetValue extends SimpleTagSupport {
	public final String TD_OPENING = "<td class='TableValue'>";
	public final String TD_OPENING_INCOMPLETE = "<td class='TableValue' ";
	public final String TD_CLOSING = "</td>";
	
	private ResultSet resultset;
	
	private String getTDOpeningNoRow(int columnCount){
		return TD_OPENING_INCOMPLETE + "colspan='" + columnCount + "'> No result available" + TD_CLOSING;
		
	}
	
	@Override
	public void doTag() throws JspException, IOException {
		if (resultset == null) {
			getJspContext().getOut().println (TD_OPENING + "No result set found" + TD_CLOSING);
			return;
		}
		
		try {
			ResultSetMetaData metadata = resultset.getMetaData();
			int columnCount = metadata.getColumnCount();
			
			JspWriter out = getJspContext().getOut();
				
			resultset.beforeFirst();
			if (!resultset.next()) {
				out.println (getTDOpeningNoRow(columnCount));
				return;
			}
			do {
				out.println("<tr>");
				
				for (int i=0; i<columnCount; i++){
					String value = resultset.getString(i+1);
					out.println (TD_OPENING + value + TD_CLOSING);
				}
				
				out.println("</tr>");
			}
			while (resultset.next());
			
			
			
		} catch (SQLException e) {
			e.printStackTrace();
			getJspContext().getOut().println (TD_OPENING + "Exception: " + e.getMessage() + TD_CLOSING);			
		}
		
	}

	public ResultSet getResultset() {
		return resultset;
	}

	public void setResultset(Object value) {
		if (value instanceof java.sql.ResultSet) {
			this.resultset = (ResultSet) value;
		}
		else this.resultset = null;
	}
}
